<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
     
      <!-- 展示随货同行单子表详情的列表 -->
      <el-table :data="subTableDetails" :stripe="true" :show-overflow-tooltip="true">
        <!-- <el-table-column label="产品编号" prop="productId" /> -->
        <el-table-column label="产品名称" prop="productName" />
        <el-table-column label="产品批次" prop="batch" width="140" />
        <el-table-column label="随货同行单数量" prop="count" width="140" />
        <el-table-column label="实际入库数量" prop="inCount" width="120" />
      </el-table>
    </el-form>

     <!-- 审核状态 -->
      <el-form-item label="审核状态" v-if="!isReadOnly">
        <el-radio-group v-model="formData.status">
          <el-radio :label="3">通过</el-radio>
          <el-radio :label="2">退回</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <!-- 查看模式下显示审核状态 -->
      <el-form-item label="审核状态" v-else>
        <el-tag :type="formData.status === 3 ? 'success' : formData.status === 2 ? 'danger' : 'info'">
          {{ formData.status === 3 ? '通过' : formData.status === 2 ? '退回' : '待审核' }}
        </el-tag>
      </el-form-item>
      
      <!-- 退回原因（仅当选择退回时显示） -->
      <el-form-item 
        label="退回原因" 
        v-if="formData.status === 2 && !isReadOnly"
      >
        <el-input 
          type="textarea" 
          v-model="formData.opinion" 
          placeholder="请输入退回原因" 
          :rows="4"
          :disabled="isReadOnly"
        />
      </el-form-item>
      
      <!-- 查看模式下显示退回原因 -->
      <el-form-item label="退回原因" v-if="formData.status === 2 && isReadOnly">
        <div class="detail-value">{{ formData.opinion || '无' }}</div>
      </el-form-item>
      
    
    <template #footer>
      <!-- 只有非查看模式才显示按钮 -->
      <div v-if="!isReadOnly">
        <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
      <!-- 查看模式只显示关闭按钮 -->
      <div v-else>
        <el-button @click="dialogVisible = false">关 闭</el-button>
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { PurchaseInOrderApi, PurchaseInOrderVO } from '@/api/spd/purchaseinorder'
import { SupplierSendOrderApi } from '@/api/erp/suppliersendorder'
import { ref, reactive, computed, watch } from 'vue'

/** ERP采购入库审批单 表单 */
defineOptions({ name: 'PurchaseInOrderForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中状态
const formType = ref('') // 表单的类型：create - 新增；update - 修改；detail - 查看
const formData = ref({
  id: undefined,
  outOrderId: undefined,
  integrateId: undefined,
  purchaseOrderId: undefined,
  priInId: undefined,
  supplierId: undefined,
  opinion: undefined,
  status: 3, // 默认审核状态为通过
  processInstanceId: undefined,
})

// 计算属性：是否为只读模式
const isReadOnly = computed(() => formType.value === 'detail')

// 动态表单验证规则 - 只在非查看模式下验证
const formRules = reactive({
  status: [{ required: !isReadOnly.value, message: '请选择审核状态', trigger: 'change' }],
  opinion: [
    { 
      validator: (rule, value, callback) => {
        if (!isReadOnly.value && formData.value.status === 2 && !value) {
          callback(new Error('退回原因不能为空'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
})

const formRef = ref() // 表单 Ref
const subTableDetails = ref([]) // 存储随货同行单子表详情

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'detail' ? '查看详情' : t('action.' + type)
  formType.value = type
  resetForm()
  
  // 修改或查看时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await PurchaseInOrderApi.getPurchaseInOrder(id)
      // 通过随货同行单 ID 查询子表详情
      if (formData.value.outOrderId) {
        subTableDetails.value = await SupplierSendOrderApi.getItemListByOutOrderId(formData.value.outOrderId)
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 只读模式不执行提交
  if (isReadOnly.value) return
  
  // 校验表单
  await formRef.value.validate()
  
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as PurchaseInOrderVO
    
    // 审核流程，根据状态设置不同的处理逻辑
    if (formType.value === 'create') {
      await PurchaseInOrderApi.createPurchaseInOrder(data)
      message.success(t('common.createSuccess'))
    } else {
      // // 审核通过或退回
      // if (data.status === 3) {
      //   await approvePurchaseInOrder(data)
      //   message.success('审核通过成功')
      // } else if (data.status === 2) {
      //   await rejectPurchaseInOrder(data)
      //   message.success('已退回并记录原因')
      // }
      
      // 无论通过还是退回，都更新订单状态
      await PurchaseInOrderApi.updateStatusPurchaseInOrder(data)
      emit('success')
    }
    
    dialogVisible.value = false
  } catch (error) {
    message.error('审核操作失败：' + error.message)
  } finally {
    formLoading.value = false
  }
}


/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    outOrderId: undefined,
    integrateId: undefined,
    purchaseOrderId: undefined,
    priInId: undefined,
    supplierId: undefined,
    opinion: undefined,
    status: 3, // 默认审核状态为通过
    processInstanceId: undefined,
  }
  subTableDetails.value = []
  formRef.value?.resetFields()
}
</script>

<style scoped>
.detail-value {
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  min-height: 40px;
  line-height: 24px;
}
</style>